<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="passwordRef" :model="ruleForm" :rules="rules" label-width="140px">
      <el-form-item :label="t('password.old_pass')" prop="old_pass">
        <el-input v-model="ruleForm.old_pass" type="password" show-password />
      </el-form-item>

      <el-form-item :label="t('password.new_pass')" prop="new_pass">
        <el-input v-model="ruleForm.new_pass" type="password" show-password minlength="6" />
      </el-form-item>

      <el-form-item :label="t('password.query')" prop="query">
        <el-input v-model="ruleForm.query" type="query" show-password minlength="6" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(passwordRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { accountUpdatePassword } from "@/api/modules/system";

const { t } = useI18n();
const ruleForm = reactive({
  old_pass: "",
  new_pass: "",
  query: ""
});
const isEqual = (rule: any, value: any, callback: any) => {
  if (ruleForm.query != ruleForm.new_pass && !value) {
    return callback(new Error(rule.message));
  }

  callback();
};

const rules = reactive<FormRules>({
  old_pass: [{ required: true, message: t("password.rule.old_pass"), trigger: "blur" }],
  new_pass: [{ required: true, message: t("password.rule.new_pass"), trigger: "blur" }],
  query: [
    { validator: isEqual, message: t("password.rule.notEqual"), trigger: "blur" },
    { required: true, message: t("password.rule.query"), trigger: "blur" }
  ]
});

const passwordRef = ref<FormInstance>();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      if (ruleForm.new_pass != ruleForm.query) {
        ElMessage.error(t("password.rule.notEqual"));
        return;
      }

      accountUpdatePassword(ruleForm).then(response => {
        if (response.code == 200) {
          dialogVisible.value = false;
          ElMessage.success("Ok");
        } else {
          ElMessage.error(response.message);
        }
      });
    } else {
      ElMessage.error(t("common.form_check_error"));
    }
  });
};

const dialogVisible = ref(false);
const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });
</script>
